package com.smart.third.web;

import com.smart.third.domain.User;
import com.smart.third.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 登录控制器
 *
 * @author junrui.wang
 * @create 2018/3/27
 */
//标注一个spring mvc的Controller类
@Controller
public class LoginController {
    private UserService userService;

    //负责处理/index.html请求
    @RequestMapping(value = "/index.html")
    public String loginPage(){
        return "login";
    }

    @RequestMapping(value = "/loginCheck.html")
    public ModelAndView loginCheck(HttpServletRequest request, LoginCommand loginCommand){
        boolean isValidUser = userService.hasMatchUser(loginCommand.getUserName(), loginCommand.getPassword());
        if(isValidUser){
            User user = userService.findUserByUserName(loginCommand.getUserName());
            user.setLastIp(request.getLocalAddr());
            user.setLastVisit(new Date());
            userService.loginSuccess(user);
            request.getSession().setAttribute("user", user);
            return new ModelAndView("main");
        } else {
            return new ModelAndView("login", "error", "用户名或密码错误");
        }
    }

    //负责处理/index.html请求
    @RequestMapping(value = "/ServletContextResource.html")
    public String servletContextResource(){
        return "ServletContextResource";
    }

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }
}
